/**
 =========================================================
 * Material Dashboard 2 React - v2.2.0
 =========================================================

 * Product Page: https://www.creative-tim.com/product/material-dashboard-react
 * Copyright 2023 Creative Tim (https://www.creative-tim.com)

 Coded by www.creative-tim.com

 =========================================================

 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 */

// @mui material components
import Grid from "@mui/material/Grid";

// Material Dashboard 2 React components
import MDBox from "components/MDBox";

// Material Dashboard 2 React example components
import DashboardLayout from "examples/LayoutContainers/DashboardLayout";
import DashboardNavbar from "examples/Navbars/DashboardNavbar";
import SearchResultsNavbar from "examples/Navbars/SearchResultsNavbar";
import Footer from "examples/Footer";
import ReportsBarChart from "examples/Charts/BarCharts/ReportsBarChart";
import ReportsLineChart from "examples/Charts/LineCharts/ReportsLineChart";
import ComplexStatisticsCard from "examples/Cards/StatisticsCards/ComplexStatisticsCard";

// Data
import reportsBarChartData from "layouts/dashboard/data/reportsBarChartData";
import reportsLineChartData from "layouts/dashboard/data/reportsLineChartData";

// Dashboard components
import Projects from "layouts/dashboard/components/Projects";
import OrdersOverview from "layouts/dashboard/components/OrdersOverview";

import axios from "axios";
import { useEffect, useState } from "react";
import MDTypography from "../../../components/MDTypography";
import MDButton from "../../../components/MDButton";

function SearchResults() {
  // const { sales, tasks } = reportsLineChartData;

  const [searchData, setSearchData] = useState([]);

  const [loading, setLoading] = useState(null); // 记录哪个商品正在收藏
  const [favorites, setFavorites] = useState({}); // 记录收藏状态

  const searchValue = localStorage.getItem("searchValue") || "";

  const response = JSON.parse(localStorage.getItem("searchResults")) || [];

  function parseNumber(value) {
    if (value.includes("万+")) {
      return parseFloat(value.replace("万+", "")) * 10000;
    } else if (value.includes("+")) {
      return parseFloat(value.replace("+", ""));
    }
    return parseFloat(value);
  }

  // // 搜索按钮触发筛选
  // const handleSearch = () => {
  //   if (searchValue.trim() === "") {
  //     // 搜索框为空，直接展示全部数据
  //     setSearchData(response);
  //   } else {
  //     // 根据 name 字段筛选
  //     const filtered = response.filter((item) =>
  //       (item.name || "").toLowerCase().includes(searchValue.trim().toLowerCase())
  //     );
  //     setSearchData(filtered);
  //   }
  // };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const category = localStorage.getItem("selectedOption") || "option1";
        console.log("Response data length:", response.length);
        console.log(category);
        let filteredData = [...response]; // 拷贝一份
        if (searchValue.trim() !== "") {
          filteredData = filteredData.filter((item) =>
            (item.name || "").toLowerCase().includes(searchValue.trim().toLowerCase())
          );
        }
        if (category === "option1") {
          setSearchData(filteredData);
        } else if (category === "option2") {
          filteredData.sort((a, b) => parseNumber(b.price || 0) - parseNumber(a.price || 0));
          setSearchData(filteredData);
        } else if (category === "option3") {
          filteredData.sort((a, b) => parseNumber(a.price || 0) - parseNumber(b.price || 0));
          setSearchData(filteredData);
        } else {
          console.error("User data is not available.");
        }
        /*alert(response.data.data.id);*/
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    };

    fetchData();
  }, []);

  useEffect(() => {
    console.log("Updated searchData:", searchData); // 在 userData 更新时查看数据
    console.log(searchData.length);
  }, [searchData]);

  const handleFavorite = async (item) => {
    setLoading(item.name);
    try {
      const token = localStorage.getItem("authToken"); // 获取 Token
      const response = await axios.post(
        "http://localhost:8848/shouCang/addShouCang",
        { name: item.name, price: item.price, image: item.image, tableId: item.id },
        {
          headers: { Authorization: `Bearer ${token}` }, // 发送请求时携带 Token
          withCredentials: true,
        }
      );

      if (response.status === 200) {
        setFavorites((prev) => ({ ...prev, [item.name]: true })); // 更新收藏状态
      }
    } catch (error) {
      console.error("收藏失败:", error);
    } finally {
      setLoading(null);
    }
  };

  return (
    <DashboardLayout>
      <SearchResultsNavbar />
      {/*主界面*/}
      <MDBox py={3}>
        <Grid container spacing={3}>
          {searchData.map((item, index) => (
            <Grid xs={12} sm={6} md={4} key={index}>
              <MDBox
                display="flex"
                flexDirection="column"
                alignItems="center"
                p={2}
                borderRadius={2}
                shadow={2}
              >
                <img src={item.image} alt="商品图片" style={{ width: "250px", height: "250px" }} />
                <MDTypography variant="h5" gutterBottom>
                  {item.name}
                </MDTypography>
                <MDTypography variant="body2" color="textSecondary">
                  评论数: {item.number}
                </MDTypography>
                <MDTypography variant="body1" color="primary">
                  价格: {item.price}
                </MDTypography>
                <MDTypography variant="body2" color="primary">
                  {item.param_info}
                </MDTypography>
                <MDTypography variant="body2" color="textSecondary">
                  <a href={item.href} target="_blank" rel="noopener noreferrer">
                    查看详情
                  </a>
                </MDTypography>
                <MDButton
                  variant="contained"
                  color={favorites[item.name] ? "success" : "primary"}
                  onClick={() => handleFavorite(item)}
                  disabled={loading === item.name} // 仅在当前点击的商品上显示加载状态
                >
                  {favorites[item.name] ? "已收藏" : "收藏"}
                </MDButton>
              </MDBox>
            </Grid>
          ))}
        </Grid>
      </MDBox>
      {/*<Footer />*/}
    </DashboardLayout>
  );
}

export default SearchResults;

{
  /*<Grid container spacing={3}>
            <Grid item xs={12} md={6} lg={3}>
              <MDBox mb={1.5}>
                <ComplexStatisticsCard
                  color="dark"
                  icon="weekend"
                  title="Bookings"
                  count={281}
                  percentage={{
                    color: "success",
                    amount: "+55%",
                    label: "than lask week",
                  }}
                />
              </MDBox>
            </Grid>
            <Grid item xs={12} md={6} lg={3}>
              <MDBox mb={1.5}>
                <ComplexStatisticsCard
                  icon="leaderboard"
                  title="Today's Users"
                  count="2,300"
                  percentage={{
                    color: "success",
                    amount: "+3%",
                    label: "than last month",
                  }}
                />
              </MDBox>
            </Grid>
            <Grid item xs={12} md={6} lg={3}>
              <MDBox mb={1.5}>
                <ComplexStatisticsCard
                  color="success"
                  icon="store"
                  title="Revenue"
                  count="34k"
                  percentage={{
                    color: "success",
                    amount: "+1%",
                    label: "than yesterday",
                  }}
                />
              </MDBox>
            </Grid>
            <Grid item xs={12} md={6} lg={3}>
              <MDBox mb={1.5}>
                <ComplexStatisticsCard
                  color="primary"
                  icon="person_add"
                  title="Followers"
                  count="+91"
                  percentage={{
                    color: "success",
                    amount: "",
                    label: "Just updated",
                  }}
                />
              </MDBox>
            </Grid>
          </Grid>
          <MDBox mt={4.5}>
            <Grid container spacing={3}>
              <Grid item xs={12} md={6} lg={4}>
                <MDBox mb={3}>
                  <ReportsBarChart
                    color="info"
                    title="website views"
                    description="Last Campaign Performance"
                    date="campaign sent 2 days ago"
                    chart={reportsBarChartData}
                  />
                </MDBox>
              </Grid>
              <Grid item xs={12} md={6} lg={4}>
                <MDBox mb={3}>
                  <ReportsLineChart
                    color="success"
                    title="daily sales"
                    description={
                      <>
                        (<strong>+15%</strong>) increase in today sales.
                      </>
                    }
                    date="updated 4 min ago"
                    chart={sales}
                  />
                </MDBox>
              </Grid>
              <Grid item xs={12} md={6} lg={4}>
                <MDBox mb={3}>
                  <ReportsLineChart
                    color="dark"
                    title="completed tasks"
                    description="Last Campaign Performance"
                    date="just updated"
                    chart={tasks}
                  />
                </MDBox>
              </Grid>
            </Grid>
          </MDBox>
          <MDBox>
            <Grid container spacing={3}>
              <Grid item xs={12} md={6} lg={8}>
                <Projects />
              </Grid>
              <Grid item xs={12} md={6} lg={4}>
                <OrdersOverview />
              </Grid>
            </Grid>
          </MDBox>*/
}
